package com.ljw.vendingmachine;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.firefly.api.FireflyApi;
import com.firefly.api.serialport.SerialPort;
import com.ljw.vendingmachine.base.BaseActivity;
import com.ljw.vendingmachine.bean.Goods;
import com.ljw.vendingmachine.bean.MessageEvent;
import com.ljw.vendingmachine.bean.TestItem;
import com.ljw.vendingmachine.test.Config;
import com.ljw.vendingmachine.utils.ByteUtil;
import com.ljw.vendingmachine.utils.Constant;
import com.ljw.vendingmachine.utils.GsonUtil;
import com.ljw.vendingmachine.utils.LogUtil;
import com.ljw.vendingmachine.utils.ZXingUtils;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class PayActivity extends BaseActivity implements SerialPort.Callback {
    @BindView(R.id.pay_goodlist)
    RecyclerView pay_goodlist;

    @BindView(R.id.tv_totalPrice)
    TextView tv_totalPrice;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.img_qrcode)
    ImageView img_qrcode;
    private BaseQuickAdapter<Goods,BaseViewHolder> car_listAdapter;
    private Timer timer;
    int startTime = 100;
    private String orderNo;
    //支付方式 1-微信 2-支付宝
    int payType = 1;
    //串口
    private SerialPort mSerialPort = null;
    //是否已支付
    boolean isPay = false;
    private Runnable runnable;
    Handler handler = new Handler();
    static boolean isPOLL = false;
    @Override
    public void afterSetContentView() {
        EventBus.getDefault().register(this);
    }

    @Override
    public int setContentView() {
        return R.layout.activity_pay;
    }

    public synchronized void setTIME(int time) {
        this.startTime = time;
    }


    /**
     * 初始化界面
     */
    @Override
    public void initView() {

        pay_goodlist.setLayoutManager(new LinearLayoutManager(this));
        HorizontalDividerItemDecoration build = new HorizontalDividerItemDecoration.Builder(this)
                .margin(R.dimen.x40, R.dimen.x40)
                .color(R.color.color_F0F0F0)
                .build();
        pay_goodlist.addItemDecoration(build);
        car_listAdapter = new BaseQuickAdapter<Goods, BaseViewHolder>(R.layout.goodscar_item, MainActivity.goodsMap) {
            @Override
            protected void convert(BaseViewHolder helper, Goods item) {
                double goodsPrice = Double.parseDouble(item.getGoodsPrice());
                int stockNum = item.getStockNum();
                helper.setText(R.id.tv_goods_name, item.getGoodsName())
                        .setText(R.id.tv_goods_price, String.valueOf(goodsPrice))
                        .setText(R.id.tv_goods_number, String.valueOf(stockNum))
                        .setText(R.id.tv_goods_sum, String.valueOf(goodsPrice * stockNum));
                helper.getView(R.id.tv_delGoods).setVisibility(View.GONE);
                // helper.addOnClickListener(R.id.tv_delGoods);
            }
        };
//        car_listAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
//            @Override
//            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
//                if (view.getId() == R.id.tv_delGoods){
//                    adapter.remove(position);
//                    MessageEvent messageEvent=new MessageEvent();
//                    messageEvent.setCode(Constant.EVENTBUS_CODE_FLUSH_TOTAL_SUMPRICE);
//                    messageEvent.setMessage("刷新总数和总价");
//                    EventBus.getDefault().post(messageEvent);
//                }
//
//            }
//        });
        pay_goodlist.setAdapter(car_listAdapter);
        Glide.with(this).asGif().load(R.drawable.loading)
                .into(img_qrcode);
    }

    /**
     * @param goods 商品列表
     * @return 拼接之后的数据
     */
    public String getQRcode(List<Goods> goods) {
        StringBuffer stringBuffer = new StringBuffer();
        int size = goods.size();
        for (int i = 0; i < size; i++) {
            Goods good = goods.get(i);
            stringBuffer.append(good.getGid()).append("-").append(good.getStockNum());
            if (i != size - 1) stringBuffer.append(",");
        }
        return stringBuffer.toString();
    }

    /**
     * @param goods 商品列表
     * @return 拼接之后的数据
     */
    public String getQRcodeResult(List<Goods> goods, boolean number) {
        StringBuffer stringBuffer = new StringBuffer();
        int size = goods.size();
        for (int i = 0; i < size; i++) {
            Goods good = goods.get(i);
            stringBuffer.append(good.getGid()).append("-").append(good.getStockNum());
            if (number)
                stringBuffer.append("-").append(good.isOutSuccess() ? 1 : 0);
            if (i != size - 1) stringBuffer.append(",");
        }
        return stringBuffer.toString();
    }

    /**
     * 初始化界面数据
     */
    @Override
    public void initData() {
        int total = 0;
        double sumPrice = 0;
        for (Goods datum : car_listAdapter.getData()) {
            int stockNum = datum.getStockNum();
            total = total + stockNum;
            double v = Double.parseDouble(datum.getGoodsPrice());
            sumPrice = sumPrice + (stockNum * v);
        }

        String sumprice_str = "需支付￥:" + sumPrice;
        tv_totalPrice.setText(sumprice_str);
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setTIME(startTime - 1);
                if (startTime == 0) {
                    if (isPay) {
                        for (Goods goods : MainActivity.goodsMap) {
                            if (!goods.isOutOver()) {
                                goods.setOutSuccess(false);
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dialog.setMessage("出货结束！");
                                //  dialog.dismiss();
                                //  {"cmd":"0204", reqtype:1,data:{ "ids":"13-2-1,14-1-1"," orderNo":"201902121234946678I10" } }
                                StringBuffer stringBuffer = new StringBuffer();
                                for (Goods goods : MainActivity.goodsMap) {
                                    stringBuffer.append(goods.getGoodsName() + (goods.isOutSuccess() ? "出货成功" : "出货失败")).append("\n");
                                }
                                dialog.setMessage(stringBuffer.toString());
                            }
                        });

                        MessageEvent mes = new MessageEvent();
                        mes.setCode(Constant.SEND_CMD);
                        mes.setData(String.format(Constant.COMD_GOODS_OUT_SECCESS, getQRcodeResult(MainActivity.goodsMap, true), orderNo));
                        EventBus.getDefault().post(mes);
                        setTIME(2);
                        isPay = false;
                    } else {
                        toMain();
                    }

                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (tv_time != null) {
                                int times = startTime - 2;
                                tv_time.setText("请在" + (times < 0 ? "0" : times) + "秒内使用" + (payType == 1 ? "微信" : "支付宝") + "完成支付!");
                            }
                        }
                    });
                }
            }
        }, 1000, 1000);
        wx_or_alipay(payType = 1);
        initSerialPort();

        runnable = new Runnable() {
            @Override
            public void run() {
                if (isPOLL && isPay) {
                    if (mSerialPort != null)
                        mSerialPort.sendHexMsg(ByteUtil.hexStr2bytes(Constant.SERIAL_PORT_GOODS_TEST_OUT));
                }
                handler.postDelayed(this, 2000);
            }
        };
        handler.postDelayed(runnable, 1000);//每两秒执行一次runnable.
    }

    @OnClick({R.id.img_wxpay, R.id.img_alipay})
    public void changePay(View v) {
        switch (v.getId()) {
            case R.id.img_wxpay:
                if (payType == 1) break;
                Glide.with(this).asGif().load(R.drawable.loading)
                        .into(img_qrcode);
                wx_or_alipay(payType = 1);
                break;
            case R.id.img_alipay:
                if (payType == 2) break;
                Glide.with(this).asGif().load(R.drawable.loading)
                        .into(img_qrcode);
                wx_or_alipay(payType = 2);
                break;
        }
    }

    private void wx_or_alipay(int type) {
        //微信支付 1
        //支付宝支付 2
        MessageEvent mes = new MessageEvent();
        mes.setCode(Constant.SEND_CMD);
        mes.setData(String.format(Constant.COMD_GET_PAY_QRCODE, type, getQRcode(MainActivity.goodsMap)));
        EventBus.getDefault().post(mes);
    }


    /**
     * 回到首页
     */
    @OnClick(R.id.tv_toMain)
    public void toMain() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 返回上一页
     */
    @OnClick(R.id.tv_Back)
    public void toBack() {
        finish();
    }

    /**
     * 页面销毁回调
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (timer != null)
            timer.cancel();
        if (mSerialPort != null)
            mSerialPort.closeSerialPort();
        if (dialog != null) dialog.dismiss();
    }

    /**
     * @param event 页面数据回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceiveData(MessageEvent event) {
        if (Constant.EVENTBUS_CODE_QRCODE == event.getCode()) {
            try {
                JSONObject jsonObject = (JSONObject) event.getData();
                String url = jsonObject.getString("url");
                orderNo = jsonObject.getString("orderNo");
//                Glide.with(this).load(url)
//                .into(img_qrcode);
                Bitmap qrImage = ZXingUtils.createQRImage(url, img_qrcode.getWidth(), img_qrcode.getHeight());
                img_qrcode.setImageBitmap(qrImage);
            } catch (JSONException e) {
                //  Toast.
                //   e.printStackTrace();
                //   dialog.setCancelable(true);
            }
        }
        //支付完成，出货
        if (Constant.EVENTBUS_CODE_PAY_SECCESS == event.getCode()) {
            isPay = true;
            isPOLL=true;
            dialog.setMessage("支付成功，正在出货...");
            dialog.show();
            //拿到出货的id和数量
            //  String ids= (String) event.getData();
            List<String> cmds = new ArrayList<>();
            for (Goods goods : MainActivity.goodsMap) {
                if (!goods.isOutOver()) {
                    int gNo = Integer.valueOf(goods.getgNo());
//                int gNo = Integer.parseInt(gridNo);
                    int checkNumer = 8 + gNo;
                    String gridNo=Integer.toHexString(gNo).toUpperCase();
                    if (gridNo.length() < 2) gridNo = "0" + gridNo;
                    else gridNo = String.valueOf(gNo);
                    String s = ByteUtil.getlast8byte(checkNumer);
                    if (s.length() < 2) s = "0" + s;
                    MessageEvent mes = new MessageEvent();
                    String format = String.format(Constant.SERIAL_COMD, String.format(Constant.SERIAL_PORT_GOODS_OUT, gridNo) + s);
                    cmds.add(format);
                    break;
                }

            }
            MessageEvent mes = new MessageEvent();
            mes.setCode(Constant.SERIALPORT_CMD);
            mes.setData(cmds);
            EventBus.getDefault().post(mes);
//
        }
        if (Constant.RE_CONNECT == event.getCode()) {
            if ((boolean) event.getData()) {
                dialog.show();
            } else {
                dialog.dismiss();
            }
        }
        //出货完成
        if (Constant.
                EVENTBUS_CODE_GOODS_OUT_SECCESS == event.getCode()) {
            dialog.setMessage("出货结束！");
            //  dialog.dismiss();
            //  {"cmd":"0204", reqtype:1,data:{ "ids":"13-2-1,14-1-1"," orderNo":"201902121234946678I10" } }
            StringBuffer stringBuffer = new StringBuffer();
            for (Goods goods : MainActivity.goodsMap) {
                stringBuffer.append(goods.getGoodsName() + (goods.isOutSuccess() ? "出货成功" : "出货失败")).append("\n");
            }
            dialog.setMessage(stringBuffer.toString());
            MessageEvent mes = new MessageEvent();
            mes.setCode(Constant.SEND_CMD);
            mes.setData(String.format(Constant.COMD_GOODS_OUT_SECCESS, getQRcodeResult(MainActivity.goodsMap, true), orderNo));
            EventBus.getDefault().post(mes);
          //  isPay = false;
            setTIME(2);
            //   toMain();
        }
        //下一条指令
        if (Constant.EVENTBUS_CODE_GOODS_OUT_SECCESS_next == event.getCode() && isPay) {
//            dialog.setMessage("出货结束！");
//            dialog.dismiss();
            //  {"cmd":"0204", reqtype:1,data:{ "ids":"13-2-1,14-1-1"," orderNo":"201902121234946678I10" } }
            List<String> cmds = new ArrayList<>();
            for (Goods goods : MainActivity.goodsMap) {
                if (!goods.isOutOver()) {
                    String gridNo = goods.getgNo();
                    int gNo = Integer.parseInt(gridNo);
                    int checkNumer = 8 + gNo;
                    if (gridNo.length() < 2) gridNo = "0" + gridNo;


                    String s = ByteUtil.getlast8byte(checkNumer);
                    if (s.length() < 2) s = "0" + s;
                    cmds.add(String.format(Constant.SERIAL_COMD, String.format(Constant.SERIAL_PORT_GOODS_OUT, gridNo) + s));
                    break;
                }

            }
            MessageEvent mes = new MessageEvent();
            mes.setCode(Constant.SERIALPORT_CMD);
            mes.setData(cmds);
            EventBus.getDefault().post(mes);
        }


    }

    //接受串口命令
    @Subscribe
    public void onSerialPort(MessageEvent event) {

        if (Constant.SERIALPORT_CMD == event.getCode()) {

            List<String> data = (List<String>) event.getData();
            LogUtil.e("出货", data.toString());
            try {
                //  dialog.setMessage("请等待，正在出货...！");
                //  dialog.show();
                for (String datum : data) {
                    mSerialPort.sendHexMsg(ByteUtil.hexStr2bytes(datum));
                }
                //  MessageEvent mes = new MessageEvent();
                //   mes.setCode(Constant.EVENTBUS_CODE_GOODS_OUT_SECCESS);
                //       mes.setData(String.format(Constant.COMD_GOODS_OUT_SECCESS, getQRcode(MainActivity.goodsMap), orderNo));
                //     EventBus.getDefault().post(mes);

            } catch (Exception r) {
                LogUtil.e("出货", "出货命令发送异常");
                //     dialog.setMessage("出货失败！");
                //   dialog.dismiss();
            }
        }
    }

    /**
     * @param bytes 串口返回的数据
     * @param i
     */
    StringBuffer stringBuffer = new StringBuffer();

    @Override
    public void onDataReceived(byte[] bytes, int i) {
        String msg = new String(bytes);
        String s = ByteUtil.bytes2HexStr(bytes, 0, i);
        stringBuffer.append(s);
        String s1 = stringBuffer.toString();
        if (s1.startsWith("8A8A") && s1.endsWith("55") && isPay) {
        LogUtil.e("收到串口数据:", s1);
        stringBuffer.delete(0, s1.length());
        String substring = s1.substring(6, 8);
        //空闲状态 开始下一条命令
        if ("8A8A07010002000000000A55".equals(s1)&& isPay) {
            text_next();
            return;
        }
        if ("01".equals(substring)&& isPay) {
            String gNo = s1.substring(8, 10);
            String s2 = s1.substring(12, 14);
            String s3 = s1.substring(18, 20);
            if ("02".equals(s2)&&"00".equals(s3)) {
                ack(gNo);
                Goods goodsByGNO = getGoodsByGNO(String.valueOf(Integer.valueOf(gNo, 16)));
                if (goodsByGNO!=null&&!goodsByGNO.isOutOver()){

                    if ("00".equals(s1.substring(16, 18))) {
                        goodsByGNO.setOutSuccess(true);
                    } else {
                        goodsByGNO.setOutSuccess(false);
                    }

                    text_next();
                }


                return;
            }

        }
        }
//        if (s1.startsWith("8A8A") && s1.endsWith("55") && isPay) {
//            stringBuffer.delete(0, s1.length());
//            LogUtil.e("onDataReceivedCmd:", s1);
////            int i1 = s1.indexOf("8A8A");
//            String substring = s1.substring(6, 8);
//            if ("02".equals(substring)) {
//
//                String gNo = s1.substring(8, 10);
//                String s2 = s1.substring(10, 12);
////                String s2 = s1.substring(12, 14);
////                String s3 = s1.substring(16, 18);
//                String s3 = s1.substring(12, 14);
//
////                    int i1 = Integer.parseInt(gNo);
//                Goods goodsByGNO = getGoodsByGNO(gNo);
//                if ("02".equals(s2)) {//成功
//                    if ("00".equals(s3)) {
//                        goodsByGNO.setOutSuccess(true);
//                    } else {
//                        goodsByGNO.setOutSuccess(false);
//                    }
//                    //确认-------------
//                    int No = Integer.parseInt(gNo);
//                    int checkNumer = 8 + No;
////                    if (gridNo.length() < 2) gridNo = "0" + gridNo;
//                    String CNUs = ByteUtil.getlast8byte(checkNumer);
//                    if (CNUs.length() < 2) CNUs = "0" + CNUs;
//                    mSerialPort.sendHexMsg(ByteUtil.hexStr2bytes(String.format(Constant.SERIAL_COMD, String.format(Constant.SERIAL_PORT_GOODS_OUT_ACK, gNo) + CNUs)));
//                    //--------------------------------
//                }else{
//                    mSerialPort.sendHexMsg(ByteUtil.hexStr2bytes(Constant.SERIAL_PORT_GOODS_TEST_OUT));
//                }
////                    if ("01".equals(s2)){//失败
////
////                    }
//
//
//
//                if (isOutOver()) return;
//                MessageEvent messageEvent = new MessageEvent();
//                messageEvent.setCode(Constant.EVENTBUS_CODE_GOODS_OUT_SECCESS_next);
//                EventBus.getDefault().post(messageEvent);
//            }
//
//        }


//        if (!TextUtils.isEmpty(msg)&&msg.length()>=21) {
//            //出货相关命令
//            if ("C2".equals(msg.substring(4,6))){
//                String gNo = msg.substring(6, 8);//货道号
//  Goods goodsByGNO = getGoodsByGNO(gNo);
//                if (goodsByGNO==null)return;
//                String result = msg.substring(8, 10);//成功 or 失败
//                if ("03".equals(result)){//成功
//                    goodsByGNO.setOutSuccess(true);
//                }
//                if ("04".equals(result)){//失败
//                    goodsByGNO.setOutSuccess(false);
//                }
//                isOutOver();
//            }
//
//        }
        //

    }

    private void text_next() {
        if (isOutOver()) return;
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setCode(Constant.EVENTBUS_CODE_GOODS_OUT_SECCESS_next);
        EventBus.getDefault().post(messageEvent);

    }

    public Goods getGoodsByGNO(String gNo) {
        for (Goods goods : MainActivity.goodsMap) {
            if (gNo.equals(goods.getgNo())) {
                return goods;
            }
        }
        return null;
    }

    public boolean isOutOver() {
        for (Goods goods : MainActivity.goodsMap) {
            if (!goods.isOutOver()) {
                return false;
            }
        }
        MessageEvent mes = new MessageEvent();
        mes.setCode(Constant.EVENTBUS_CODE_GOODS_OUT_SECCESS);
        //  mes.setData(String.format(Constant.COMD_GOODS_OUT_SECCESS, getQRcode(MainActivity.goodsMap,true), orderNo));
        EventBus.getDefault().post(mes);
        return true;
    }

    /**
     * 初始化串口
     */
    public void initSerialPort() {

        if (!openSerialPort(Constant.SERIAL_PORT_PATH, Constant.SERIAL_PORT_BAUDRATE)) {
            dialog.setMessage("柜机设备异常");
            dialog.show();
        }

    }

    /**
     * @param path     设备路径
     * @param baudrate 波特率
     * @return 是否打开成功
     */
    private boolean openSerialPort(String path, int baudrate) {
        if (mSerialPort != null) mSerialPort.closeSerialPort();
        mSerialPort = null;
        try {
            mSerialPort = new SerialPort(new File(path), baudrate, 0);
            mSerialPort.setCallback(this);
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtil.d("openSerialPort", "open serialport(" + path + ") error:" + e.toString());
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            LogUtil.d("openSerialPort", "open serialport(" + path + ") error:" + e.toString());
            return false;
        }
        return true;

    }

    /**
     * 回复串口确认消息
     */
    public void ack(String gNo){
        int gNumber = Integer.valueOf(gNo,16);
        int checkNumer = 7 + gNumber;
        gNo=Integer.toHexString(gNumber);
        if (gNo.length()<2)gNo="0"+gNo;
        String che = ByteUtil.getlast8byte(checkNumer);
        if (che.length() < 2) che = "0" + che;
        String format = String.format("8A8A0303%s01%s55", gNo, che);
        LogUtil.e("回复 ack:","通道号："+gNo+ "命令："+ format);
    }
}
